<template>
  <el-scrollbar style="height: 100%" id="scroll">
    <el-form :model="formData" class="classInfo-container" label-width="180px" label-position="top">
      <el-page-header @back="goBack"></el-page-header>
      <p align="center">开课表</p>
      <div align="right">
        <div>
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div align="center">
              <label style="font-size: 14px">封面上传</label>
            </div>
          </el-upload>
        </div>
      </div>
      <el-form-item label="课程名称：">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="课程简介：">
        <el-input type="textarea" v-model="formData.info"></el-input>
      </el-form-item>
      <el-form-item width="100%">
        <el-col :span="4">开课:</el-col>
        <el-col :span="2" style="margin-left: 74%">
          <el-button
            @click="addSchedule"
            circle
            type="primary"
            icon="el-icon-plus"
            size="mini"
            style="text-align: right"
          ></el-button>
        </el-col>
      </el-form-item>

      <el-form-item
        v-for="(schedule,index) in formData.schedules"
        :key="schedule.key"
        :prop="'schedules.'+ index+'.value'"
      >
        <div style="text-align: left">
          <el-col :span="7">
            <el-input v-model="schedule.title" placeholder="请输入小标题"></el-input>
          </el-col>
          <el-col :span="6" style="margin-left: 1%">
            <el-date-picker
              style="width: 140px"
              v-model="schedule.date"
              type="date"
              placeholder="请选择日期"
            ></el-date-picker>
          </el-col>
          <el-col :span="6" style="margin-left: 6.5%">
            <el-select style="width: 131px;" v-model="schedule.timeId" placeholder="请选择时间段">
              <el-option
                v-for="item in courseType"
                :key="item.index"
                :label="item.name"
                :value="item.index"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="2" style="margin-left: 5%">
            <el-button
              type="danger"
              size="mini"
              circle
              v-show="formData.schedules.length>1"
              @click.prevent="removeSchedule(schedule)"
            >
              <i class="el-icon-close"></i>
            </el-button>
          </el-col>
        </div>
      </el-form-item>

      <el-form-item>
        <div style="text-align: right">
          <el-button type="primary" align="center" @click="onSubmit">提交</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-scrollbar>
</template>
<script>
export default {
  name: 'addCourse',
  data () {
    return {
      courseType: [
        { index: 0, name: '10:00-11:00' },
        { index: 1, name: '11:00-12:00' },
        { index: 2, name: '14:00-15:00' },
        { index: 3, name: '15:00-16:00' },
        { index: 4, name: '16:00-17:00' },
        { index: 5, name: '19:00-20:00' },
        { index: 6, name: '20:00-21:00' }
      ],
      imageUrl: '',
      formData: {
        uid: window.sessionStorage.token,
        title: 'aa',
        info: '简介',
        pic: null,
        schedules: [
          {
            timeId: null,
            date: null,
            title: ''
          }
        ]
      }
    }
  },
  methods: {
    // 提交
    onSubmit () {
      var that = this
      var form = new FormData()
      form.append('uid', that.formData.uid)

      if (that.formData.title == null || that.formData.title == '') {
        that.$message.error('课程名称不能为空')
        return false
      }
      form.append('title', that.formData.title)

      if (that.formData.info == null || that.formData.info == '') {
        that.$message.error('课程简介不能为空')
        return false
      }
      form.append('info', that.formData.info)

      if (that.formData.pic == null) {
        that.$message.error('课程封面不能为空')
        return false
      }
      form.append('pic', that.formData.pic)
      var len = that.formData.schedules.length
      for (var i = 0; i < len; i++) {
        if (
          that.formData.schedules[i].title == null ||
          that.formData.schedules[i].title == ''
        ) {
          that.$message.error('小课名称不能为空')
          return false
        }
        if (
          that.formData.schedules[i].date == null ||
          that.formData.schedules[i].date == ''
        ) {
          that.$message.error('开课日期不能为空')
          return false
        }

        var now = new Date()
        if (that.formData.schedules[i].date <= now) {
          that.$message.error('开课日期不能早于明天')
          return false
        }

        if (
          that.formData.schedules[i].timeId == null ||
          that.formData.schedules[i].timeId < 0
        ) {
          // console.log(that.formData.schedules[i].timeId)
          that.$message.error('开课时间段不能为空')
          return false
        }
        that.formData.schedules[i].date = that.formatDateTime(
          that.formData.schedules[i].date
        )
      }
      var schedules = JSON.stringify(that.formData.schedules)
      form.append('schedules', schedules)

      that
        .uploadFileRequest('/api/course/add', form)
        .then(resp => {
          if (resp && resp.status == 200) {
            that.$message.success('课程添加成功！')
          } else {
            that.$message.error('课程添加失败，请重新添加！')
          }
        })
        .catch(err => {
          that.$message.error('出错啦啦啦！')
        })
    },

    // 时间转换函数，Date转成yyyy-MM-dd
    formatDateTime (date) {
      date = new Date(Date.parse(date))
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      return y + '-' + m + '-' + d
    },
    // 返回
    goBack () {
      this.$router.push('/schedule')
    },
    // 获取图片
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 图片校验
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传封面图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传封面图片大小不能超过 2MB!')
        return false
      }
      this.formData.pic = file
      return true
    },
    // 增加表单项
    addSchedule () {
      this.formData.schedules.push({
        timeId: null,
        date: null,
        title: ''
      })
      window.scrollTo(0, document.body.scrollHeight)
    },
    // 删除表单项
    removeSchedule (item) {
      var index = this.formData.schedules.indexOf(item)
      if (index !== -1) {
        this.formData.schedules.splice(index, 1)
      }
    }
  }
}
</script>
<style scoped>
.classInfo-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: auto;
  margin-top: 20px;
  width: 450px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}

.avatar-uploader .el-upload {
  border: 1px solid #000;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>
